const fs = require("fs");
const path = require("path");
const config = require("../app.config");
const mkdirp = require("mkdirp");

/*功能:异步读取文件
 *@param:fileName 名称
 **/
const readFile = function(fileName) {
  let filePath = config.basePath + "/" + fileName;
  return new Promise(function(resolve, reject) {
    fs.readFile(filePath, function(error, data) {
      if (error) return reject(error);
      resolve(data);
    });
  });
};
/*功能:异步写入文件
 *@param:dir 文件路径
 *fileName:文件名称
 *data:要写入的数据
 **/
const writeFile = async function(dir, fileName, data) {
  let filePath = path.join(config.basePath, "/", dir);
  fileName = path.join(filePath, "/", fileName);
  await mkdirp(filePath);
  let result = await fs.writeFile(fileName, data, function(err) {
    if (err) return err;
    console.log("写入成功");
  });
  return result;
};
module.exports = {
  readFile: readFile,
  writeFile: writeFile
};
